package Cliente;

import Cliente.view.*;
import Servidor.GerenciadorArquivo;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

/**
 *
 * @author Douglas
 */
public class Cliente {

    private Socket socketCliente;
    private static Cliente cliente = new Cliente();

    private Cliente() {
        new File("FTP" + File.separator + "arquivos").mkdirs();
    }

    public static Cliente getCliente() {
        return cliente;
    }

    public void Conectar() {
        try {//192.168.1.4
            socketCliente = new Socket("localhost", 6666);
            socketCliente.setKeepAlive(true);
        } catch (UnknownHostException ex) {
            Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("STATUS--->" + socketCliente.isConnected() + "//PORTA LOCAL--->" + socketCliente.getLocalPort() + "//IP--->" + socketCliente.getInetAddress() + "//PORTA--->" + socketCliente.getPort());

    }

    public String EnviaMSG(String mensagem) {

        //DataOutputStream out = new DataOutputStream (new BufferedOutputStream(socketCliente.getOutputStream()) );

        try {
            DataOutputStream out = new DataOutputStream(socketCliente.getOutputStream()); //fluxo pra escrever pro server        
            BufferedReader in = new BufferedReader(new InputStreamReader(socketCliente.getInputStream())); //fluxo pra ler do server

            out.writeBytes(mensagem + "\n");
            out.flush();
            System.out.println("ENVIOU");

            mensagem = in.readLine();
            System.out.println("RECEBEU--->" + mensagem);
            //socketCliente.close();
            //out.close();
            //in.close();
            return mensagem;


        } catch (IOException ex) {
            Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
    public String getListFiles(String email) {
        String mensagem = ":LST:";
        try {
            DataOutputStream out = new DataOutputStream(socketCliente.getOutputStream()); //fluxo pra escrever pro server        
            BufferedReader in = new BufferedReader(new InputStreamReader(socketCliente.getInputStream())); //fluxo pra ler do server

            out.writeBytes(mensagem + "\n");
            out.flush();
            mensagem = in.readLine();
            System.out.println("Server RECEBEU--->" + mensagem);
            out.writeBytes(email + "\n");
            out.flush();

            ObjectInputStream inputArc = new ObjectInputStream(new BufferedInputStream(socketCliente.getInputStream()));
            String fileName = inputArc.readUTF();
            long size = inputArc.readLong();

            System.out.println("Processando arquivo: " + fileName + " - " + size + " bytes.");
            String path = "FTP" + File.separator + "arquivos" + File.separator + fileName;
            BufferedOutputStream saveArq = new BufferedOutputStream(new FileOutputStream(path));
            byte[] buf = new byte[4096];
            int temp = 0;
            while (true) {
                int len;
                if (size - temp > 0) {
                    len = inputArc.read(buf);
                } else {
                    saveArq.close();
                    break;
                }
                temp = temp + len;
                System.out.println("Quanto ja veio-->" + temp + "//" + size);


                saveArq.write(buf, 0, len);
                saveArq.flush();
            }

            //socketCliente.close();
            //out.close();
            //in.close();
            return mensagem;
        } catch (IOException ex) {
            Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
    
    public String share(String fileName, String user) {
        try {
            DataOutputStream out = new DataOutputStream(socketCliente.getOutputStream()); //fluxo pra escrever pro server        
            BufferedReader in = new BufferedReader(new InputStreamReader(socketCliente.getInputStream())); //fluxo pra ler do server

            out.writeBytes(":SHARE:\n");
            out.flush();
            String mensagem = in.readLine();
            System.out.println("Servidor recebeu mensagem de compartilhamento");
            out.writeBytes(user + "\n");
            out.writeBytes(fileName + "\n");
            String message = in.readLine();
            out.flush();
            return message;
        } catch(Exception e) {
            e.printStackTrace();
        }
        return "Ocorreu um erro";
    }

    public void SendArc(String nomeArq) {

        try {
            File file = new File(nomeArq);
            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socketCliente.getOutputStream()));
            System.out.println("Transferindo o arquivo: " + file.getName());
            out.writeUTF(file.getName());
            out.writeLong(file.length());
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));

            byte[] buf = new byte[4096];
            while (true) {
                int len = in.read(buf);
                if (len == -1) {
                    break;
                }
                out.write(buf, 0, len);
                out.flush();
            }

            System.out.println("Arquivo enviado com sucesso");
            //out.close();
            in.close();

        } catch (FileNotFoundException ex) {
            Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void useFTP(String directoryName, String nameFiletoUpload,
            String dirFiletoUpload) {

        String ftpserver = "192.168.0.114";
        String username = "Douglas";
        String password = "0000";
        FTPClient ftpClient = new FTPClient();

        try {
            ftpClient.connect(ftpserver);
            System.out.print(ftpClient.getReplyString());

            // check reply code.  
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                ftpClient.disconnect();
                System.out.println("Connection refused.");
                return;
            }

            ftpClient.login(username, password);
            System.out.println("Workdir >>"
                    + ftpClient.printWorkingDirectory());
            ftpClient.changeWorkingDirectory(directoryName);

            //Store file start  
            FileInputStream inp = new FileInputStream(dirFiletoUpload);
            BufferedInputStream input = new BufferedInputStream(inp);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.storeFile(nameFiletoUpload, input);
            //Store file end  

            //List all Files and directories  
            FTPFile[] files = ftpClient.listFiles();

            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    //If file print name and size  
                    if (files[i].isFile()) {
                        System.out.println("File >> " + files[i].getName()
                                + "   Size >>" + files[i].getSize());
                    }
                }
            }
            System.out.println("getStatus " + ftpClient.getStatus("/www"));
            System.out.println("getSystemName " + ftpClient.getSystemName());
            System.out.println("listHelp " + ftpClient.listHelp());
            System.out.println("listNames " + ftpClient.listNames());
            ftpClient.logout();
            ftpClient.disconnect();
        } catch (IOException e) {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException f) {
                    // do nothing  
                }
            }

            e.printStackTrace();
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        //new Login().setVisible(true);
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        Cliente.getCliente().Conectar();
        //MainMenu mainMenu = new MainMenu();
        //mainMenu.setVisible(true);
        Login login = new Login();
        login.setVisible(true);
    }
}
